package org.example.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

//@Configuration // 加到了springConfig中
public class MyBatisConfig {
    /*
    *
    *   MyBatis 的主配置文件
    *   配置内容:
    *       1. 配置数据源(已经在JdbcConfig中配置完毕了)
    *       2. 配置实体类别名
    *       3. 配置mapper注册
    *
    * */

    // 配置实体类别名
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean ssfBean = new SqlSessionFactoryBean();
        ssfBean.setTypeAliasesPackage("org.example.entity");// 批量配置别名,别名就是类名
        ssfBean.setDataSource(dataSource);

        // 复杂的sql直接写在AccountMapper.xml映射文件里 需要有如下配置
        ssfBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

        return ssfBean;
    }

    // 配置mapper注册
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("org.example.mapper");
        return msc;
    }
}
